/**
 * 主应用类
 * 管理整个应用的状态和交互
 */
class App {
    constructor() {
        this.uploadManager = null;
        this.settings = this.loadSettings();
        this.init();
    }

    /**
     * 初始化应用
     */
    init() {
        this.initUploadManager();
        this.bindEvents();
        this.updateUI();
    }

    /**
     * 初始化上传管理器
     */
    initUploadManager() {
        this.uploadManager = new UploadManager({
            baseUrl: this.settings.baseUrl,
            chunkSize: parseInt(this.settings.chunkSize),
            maxConcurrent: parseInt(this.settings.maxConcurrent),
            allowedTypes: [], // 允许所有类型
            maxFileSize: 3 * 1024 * 1024 * 1024, // 3GB
            onTaskStart: (task) => this.onTaskStart(task),
            onTaskProgress: (task) => this.onTaskProgress(task),
            onTaskComplete: (task) => this.onTaskComplete(task),
            onTaskError: (task) => this.onTaskError(task),
            onQueueUpdate: (data) => this.onQueueUpdate(data)
        });
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 文件选择
        const fileInput = document.getElementById('fileInput');
        fileInput.addEventListener('change', (e) => {
            this.handleFiles(e.target.files);
            e.target.value = ''; // 清空input，允许重复选择同一文件
        });

        // 拖拽上传
        const uploadArea = document.getElementById('uploadArea');
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            this.handleFiles(e.dataTransfer.files);
        });

        // 点击上传区域
        uploadArea.addEventListener('click', () => {
            document.getElementById('fileInput').click();
        });

        // 设置面板
        this.loadSettingsToUI();
    }

    /**
     * 处理文件选择
     */
    handleFiles(files) {
        if (files.length === 0) return;

        const options = {
            projectId: this.settings.projectId,
            userId: this.settings.userId
        };

        this.uploadManager.addFiles(files, options);
        this.showNotification('success', `已添加 ${files.length} 个文件到上传队列`);
    }

    /**
     * 任务开始回调
     */
    onTaskStart(task) {
        this.addTaskToUI(task);
        this.updateStats();
        this.showNotification('info', `开始上传: ${task.file.name}`);
    }

    /**
     * 任务进度回调
     */
    onTaskProgress(task) {
        this.updateTaskInUI(task);
        this.updateStats();
    }

    /**
     * 任务完成回调
     */
    onTaskComplete(task) {
        this.updateTaskInUI(task);
        this.updateStats();
        this.showNotification('success', `上传完成: ${task.file.name}`);
    }

    /**
     * 任务错误回调
     */
    onTaskError(task) {
        this.updateTaskInUI(task);
        this.updateStats();
        
        if (task.errors) {
            // 文件验证错误
            this.showNotification('error', `文件验证失败: ${task.file.name} - ${task.errors.join(', ')}`);
        } else {
            // 上传错误
            this.showNotification('error', `上传失败: ${task.file.name} - ${task.error}`);
        }
    }

    /**
     * 队列更新回调
     */
    onQueueUpdate(data) {
        this.updateStats();
    }

    /**
     * 添加任务到UI
     */
    addTaskToUI(task) {
        const tasksList = document.getElementById('tasksList');
        
        // 移除空状态
        const emptyState = tasksList.querySelector('.empty-state');
        if (emptyState) {
            emptyState.remove();
        }

        const taskElement = this.createTaskElement(task);
        tasksList.insertBefore(taskElement, tasksList.firstChild);
    }

    /**
     * 创建任务元素
     */
    createTaskElement(task) {
        const div = document.createElement('div');
        div.className = 'task-item fade-in';
        div.id = `task-${task.id}`;
        
        div.innerHTML = `
            <div class="task-header">
                <div class="task-info">
                    <div class="task-name">${task.file.name}</div>
                    <div class="task-meta">
                        <span><i class="fas fa-hdd"></i> ${ChunkUploader.formatFileSize(task.file.size)}</span>
                        <span><i class="fas fa-clock"></i> ${new Date().toLocaleTimeString()}</span>
                        ${task.fileId ? `<span><i class="fas fa-fingerprint"></i> ${task.fileId}</span>` : ''}
                    </div>
                </div>
                <div class="task-actions">
                    <span class="task-status ${task.status}">${this.getStatusText(task.status)}</span>
                    ${this.getTaskActionButtons(task)}
                </div>
            </div>
            <div class="progress-container">
                <div class="progress-bar">
                    <div class="progress-fill" style="width: ${task.progress || 0}%"></div>
                </div>
                <div class="progress-text">
                    <span>${task.progress || 0}% (${task.uploadedChunks || 0}/${task.totalChunks || 0} 分片)</span>
                    <span>${this.getTaskDuration(task)}</span>
                </div>
            </div>
        `;

        return div;
    }

    /**
     * 更新任务UI
     */
    updateTaskInUI(task) {
        const taskElement = document.getElementById(`task-${task.id}`);
        if (!taskElement) return;

        // 更新状态
        const statusElement = taskElement.querySelector('.task-status');
        statusElement.className = `task-status ${task.status}`;
        statusElement.textContent = this.getStatusText(task.status);

        // 更新进度
        const progressFill = taskElement.querySelector('.progress-fill');
        progressFill.style.width = `${task.progress || 0}%`;

        const progressText = taskElement.querySelector('.progress-text');
        progressText.innerHTML = `
            <span>${task.progress || 0}% (${task.uploadedChunks || 0}/${task.totalChunks || 0} 分片)</span>
            <span>${this.getTaskDuration(task)}</span>
        `;

        // 更新操作按钮
        const actionsElement = taskElement.querySelector('.task-actions');
        const statusElement2 = actionsElement.querySelector('.task-status');
        actionsElement.innerHTML = '';
        actionsElement.appendChild(statusElement2);
        actionsElement.insertAdjacentHTML('beforeend', this.getTaskActionButtons(task));

        // 更新文件ID
        if (task.fileId) {
            const metaElement = taskElement.querySelector('.task-meta');
            if (!metaElement.querySelector('.file-id')) {
                metaElement.insertAdjacentHTML('beforeend', 
                    `<span class="file-id"><i class="fas fa-fingerprint"></i> ${task.fileId}</span>`
                );
            }
        }
    }

    /**
     * 获取状态文本
     */
    getStatusText(status) {
        const statusMap = {
            pending: '等待中',
            uploading: '上传中',
            completed: '已完成',
            failed: '失败',
            cancelled: '已取消'
        };
        return statusMap[status] || status;
    }

    /**
     * 获取任务操作按钮
     */
    getTaskActionButtons(task) {
        switch (task.status) {
            case 'pending':
                return `<button class="btn btn-sm btn-danger" onclick="app.cancelTask('${task.id}')">
                    <i class="fas fa-times"></i> 取消
                </button>`;
            case 'uploading':
                return `<button class="btn btn-sm btn-danger" onclick="app.cancelTask('${task.id}')">
                    <i class="fas fa-stop"></i> 停止
                </button>`;
            case 'failed':
                return `<button class="btn btn-sm btn-success" onclick="app.retryTask('${task.id}')">
                    <i class="fas fa-redo"></i> 重试
                </button>`;
            case 'completed':
            case 'cancelled':
                return `<button class="btn btn-sm btn-secondary" onclick="app.removeTask('${task.id}')">
                    <i class="fas fa-trash"></i> 移除
                </button>`;
            default:
                return '';
        }
    }

    /**
     * 获取任务持续时间
     */
    getTaskDuration(task) {
        if (!task.startTime) return '';
        
        const endTime = task.endTime || Date.now();
        const duration = Math.floor((endTime - task.startTime) / 1000);
        
        if (duration < 60) {
            return `${duration}秒`;
        } else if (duration < 3600) {
            return `${Math.floor(duration / 60)}分${duration % 60}秒`;
        } else {
            const hours = Math.floor(duration / 3600);
            const minutes = Math.floor((duration % 3600) / 60);
            return `${hours}时${minutes}分`;
        }
    }

    /**
     * 更新统计信息
     */
    updateStats() {
        const stats = this.uploadManager.getStatistics();
        
        document.getElementById('totalTasks').textContent = stats.total;
        document.getElementById('pendingTasks').textContent = stats.pending;
        document.getElementById('uploadingTasks').textContent = stats.uploading;
        document.getElementById('completedTasks').textContent = stats.completed;
        document.getElementById('failedTasks').textContent = stats.failed;
    }

    /**
     * 取消任务
     */
    cancelTask(taskId) {
        this.uploadManager.cancelTask(taskId);
    }

    /**
     * 重试任务
     */
    retryTask(taskId) {
        this.uploadManager.retryTask(taskId);
    }

    /**
     * 移除任务
     */
    removeTask(taskId) {
        const taskElement = document.getElementById(`task-${taskId}`);
        if (taskElement) {
            taskElement.remove();
        }
        
        // 如果没有任务了，显示空状态
        const tasksList = document.getElementById('tasksList');
        if (tasksList.children.length === 0) {
            tasksList.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>暂无上传任务</p>
                </div>
            `;
        }
    }

    /**
     * 清除已完成的任务
     */
    clearCompleted() {
        const count = this.uploadManager.clearCompleted();
        
        // 移除UI中已完成的任务
        const completedTasks = document.querySelectorAll('.task-item .task-status.completed, .task-item .task-status.cancelled');
        completedTasks.forEach(status => {
            status.closest('.task-item').remove();
        });
        
        // 检查是否需要显示空状态
        const tasksList = document.getElementById('tasksList');
        if (tasksList.children.length === 0) {
            tasksList.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>暂无上传任务</p>
                </div>
            `;
        }
        
        if (count > 0) {
            this.showNotification('success', `已清除 ${count} 个已完成的任务`);
        }
    }

    /**
     * 暂停所有上传
     */
    pauseAll() {
        this.uploadManager.pauseAll();
        this.showNotification('info', '已暂停所有上传任务');
    }

    /**
     * 恢复所有上传
     */
    resumeAll() {
        this.uploadManager.resumeAll();
        this.showNotification('info', '已恢复所有上传任务');
    }

    /**
     * 切换设置面板
     */
    toggleSettings() {
        const panel = document.getElementById('settingsPanel');
        panel.classList.toggle('active');
    }

    /**
     * 加载设置到UI
     */
    loadSettingsToUI() {
        document.getElementById('baseUrl').value = this.settings.baseUrl;
        document.getElementById('chunkSize').value = this.settings.chunkSize;
        document.getElementById('maxConcurrent').value = this.settings.maxConcurrent;
        document.getElementById('projectId').value = this.settings.projectId;
        document.getElementById('userId').value = this.settings.userId;
    }

    /**
     * 保存设置
     */
    saveSettings() {
        this.settings = {
            baseUrl: document.getElementById('baseUrl').value,
            chunkSize: document.getElementById('chunkSize').value,
            maxConcurrent: document.getElementById('maxConcurrent').value,
            projectId: document.getElementById('projectId').value,
            userId: document.getElementById('userId').value
        };

        localStorage.setItem('uploadSettings', JSON.stringify(this.settings));
        
        // 重新初始化上传管理器
        this.initUploadManager();
        
        this.showNotification('success', '设置已保存');
        this.toggleSettings();
    }

    /**
     * 加载设置
     */
    loadSettings() {
        const defaultSettings = {
            baseUrl: '/api/notebook/environment',
            chunkSize: '2097152', // 2MB
            maxConcurrent: '3',
            projectId: 'default',
            userId: 'user1'
        };

        try {
            const saved = localStorage.getItem('uploadSettings');
            return saved ? { ...defaultSettings, ...JSON.parse(saved) } : defaultSettings;
        } catch (error) {
            return defaultSettings;
        }
    }

    /**
     * 显示通知
     */
    showNotification(type, message, duration = 5000) {
        const notifications = document.getElementById('notifications');
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: #6b7280;">×</button>
            </div>
        `;
        
        notifications.appendChild(notification);
        
        // 自动移除
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, duration);
    }

    /**
     * 更新UI
     */
    updateUI() {
        this.updateStats();
    }
}

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new App();
});

